package com.dms.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.order.entity.Order;
import com.dms.modules.order.service.OrderService;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.entity.ProductComment;
import com.dms.modules.product.mapper.ProductCommentMapper;
import com.dms.modules.product.service.ProductCommentService;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.product.vo.CommentVO;
import com.dms.modules.product.vo.CommentStatisticsVO;
import com.dms.modules.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 商品评论服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductCommentServiceImpl extends ServiceImpl<ProductCommentMapper, ProductComment> implements ProductCommentService {

    private final ProductService productService;
    private final UserService userService;
    private final OrderService orderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addComment(Long userId, Long orderId, Long productId, String content, Integer rating, List<String> images, Boolean isAnonymous) {
        // 1. 验证订单状态
        Order order = orderService.getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("不能评价其他用户的订单");
        }
        if (order.getStatus() != 3) { // 假设3表示已完成状态
            throw new BusinessException("只能评价已完成的订单");
        }

        // 2. 验证商品是否在订单中
        boolean productInOrder = orderService.isProductInOrder(orderId, productId);
        if (!productInOrder) {
            throw new BusinessException("该商品不在订单中");
        }

        // 3. 验证是否已评价
        int reviewCount = baseMapper.checkHasReviewed(orderId, productId);
        if (reviewCount > 0) {
            throw new BusinessException("该商品已评价");
        }

        // 4. 创建评论
        ProductComment comment = new ProductComment();
        comment.setUserId(userId);
        comment.setOrderId(orderId);
        comment.setProductId(productId);
        comment.setContent(content);
        comment.setRating(rating);
        comment.setImages(images);
        comment.setIsAnonymous(isAnonymous != null && isAnonymous);
        comment.setStatus(1); // 直接设置为已通过状态
        comment.setLikeCount(0);
        comment.setHasReviewed(true);
        comment.setCreateTime(LocalDateTime.now());
        
        save(comment);
        return comment.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean replyComment(Long commentId, String reply, Long userId) {
        if (!StringUtils.hasText(reply)) {
            throw new BusinessException("回复内容不能为空");
        }
        
        ProductComment comment = getById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }
        
        comment.setReply(reply);
        comment.setReplyTime(LocalDateTime.now());
        return updateById(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteComment(Long commentId, Long userId) {
        ProductComment comment = getById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }
        
        if (!comment.getUserId().equals(userId)) {
            throw new BusinessException("无权删除该评论");
        }
        
        return removeById(commentId);
    }

    @Override
    public IPage<CommentVO> getProductComments(Long productId, Page<CommentVO> page) {
        log.info("获取商品[{}]的评论列表, 页码: {}, 每页数量: {}", productId, page.getCurrent(), page.getSize());
        try {
            // 检查商品是否存在
            Product product = productService.getById(productId);
            if (product == null) {
                log.warn("商品[{}]不存在", productId);
                return new Page<>();
            }
            
            // 查询评论列表
            IPage<CommentVO> comments = baseMapper.getProductComments(productId, page);
            
            // 处理评论数据
            if (comments != null && comments.getRecords() != null) {
                comments.getRecords().forEach(comment -> {
                    // 处理匿名评论
                    if (Boolean.TRUE.equals(comment.getIsAnonymous())) {
                        comment.setNickname("匿名用户");
                        comment.setAvatar(null);
                    }
                    // 处理评论图片
                    if (comment.getImages() != null && !comment.getImages().isEmpty()) {
                        try {
                            ObjectMapper mapper = new ObjectMapper();
                            comment.setImages(mapper.readValue(comment.getImages().toString(), new TypeReference<List<String>>() {}));
                        } catch (Exception e) {
                            log.error("解析评论图片失败: {}", e.getMessage());
                            comment.setImages(new ArrayList<>());
                        }
                    }
                });
            }
            
            log.info("获取商品[{}]的评论列表成功, 总数: {}", productId, comments.getTotal());
            return comments;
        } catch (Exception e) {
            log.error("获取商品[{}]的评论列表失败: {}", productId, e.getMessage(), e);
            return new Page<>();
        }
    }

    @Override
    public IPage<CommentVO> getUserComments(Long userId, Page<CommentVO> page) {
        return baseMapper.getUserComments(userId, page);
    }

    @Override
    public CommentVO getCommentDetail(Long commentId) {
        log.info("获取评论详情, 评论ID: {}", commentId);
        try {
            CommentVO comment = baseMapper.getCommentDetail(commentId);
            if (comment == null) {
                log.warn("评论不存在, 评论ID: {}", commentId);
                return null;
            }

            // 处理匿名评论
            if (Boolean.TRUE.equals(comment.getIsAnonymous())) {
                comment.setNickname("匿名用户");
                comment.setAvatar(null);
            }

            // 处理评论图片
            if (comment.getImages() != null) {
                try {
                    String imagesStr = comment.getImages().toString();
                    // 移除开头和结尾的方括号
                    if (imagesStr.startsWith("[") && imagesStr.endsWith("]")) {
                        imagesStr = imagesStr.substring(1, imagesStr.length() - 1);
                    }
                    // 处理引号
                    imagesStr = imagesStr.replace("\"\"", "\"");
                    if (imagesStr.startsWith("\"") && imagesStr.endsWith("\"")) {
                        imagesStr = imagesStr.substring(1, imagesStr.length() - 1);
                    }
                    
                    List<String> imageList = new ArrayList<>();
                    if (!imagesStr.isEmpty()) {
                        imageList.add(imagesStr);
                    }
                    comment.setImages(imageList);
                    
                    log.debug("处理后的图片列表: {}", imageList);
                } catch (Exception e) {
                    log.error("解析评论图片失败: {}", e.getMessage());
                    comment.setImages(new ArrayList<>());
                }
            }

            log.info("获取评论详情成功, 评论ID: {}", commentId);
            return comment;
        } catch (Exception e) {
            log.error("获取评论详情失败, 评论ID: {}", commentId, e);
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleLike(Long commentId, Long userId) {
        ProductComment comment = getById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }
        
        // 检查是否已点赞
        boolean hasLiked = baseMapper.hasLiked(commentId, userId);
        if (hasLiked) {
            // 取消点赞
            baseMapper.unlikeComment(commentId, userId);
            comment.setLikeCount(comment.getLikeCount() - 1);
        } else {
            // 添加点赞
            baseMapper.likeComment(commentId, userId);
            comment.setLikeCount(comment.getLikeCount() + 1);
        }
        
        return updateById(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditComment(Long commentId, Integer status, String remark) {
        ProductComment comment = getById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }
        
        comment.setStatus(status);
        comment.setAuditRemark(remark);
        comment.setAuditTime(LocalDateTime.now());
        return updateById(comment);
    }

    @Override
    public CommentStatisticsVO getCommentStatistics(Long productId) {
        return baseMapper.getCommentStatistics(productId);
    }
    
    @Override
    public int checkHasReviewed(Long orderId, Long productId) {
        return baseMapper.checkHasReviewed(orderId, productId);
    }
    
    /**
     * 检查用户是否已评论
     */
    private boolean hasCommented(Long orderId, Long productId) {
        LambdaQueryWrapper<ProductComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductComment::getOrderId, orderId)
               .eq(ProductComment::getProductId, productId);
        return count(wrapper) > 0;
    }
} 